package com.zmn.oms.admin.controller.work.list;

import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto.LayuiTableResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.mcc.cas.web.StaffAdminService;
import com.zmn.oms.common.constant.OmsPageConsts;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.vo.TabQueryVO;
import com.zmn.oms.model.entity.work.OrderWorkOperateQuery;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.oms.model.vo.work.list.ZsOrderWorkCustomerServiceVO;
import com.zmn.oms.zmn.business.interfaces.work.list.ZsOrderWorkCustomerServiceQueryBService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 类描述：话务工单列表controller
 *
 * @author lujia
 * @date 2018/11/07 16:32
 */
@Controller
@RequestMapping("/customerservice/work")
public class WorkCustomerServiceListController extends WorkListTabBaseController {

    @Autowired
    ZsOrderWorkCustomerServiceQueryBService zsOrderWorkCustomerServiceQueryBService;
    private Logger logger = LoggerFactory.getLogger(WorkCustomerServiceListController.class);

    /**
     * 工单列表
     */
    // @RequiresPermissions("/zs/customerservice/work/list.action")
    @RequestMapping(value = "/list")
    public ModelAndView list(OrderWorkQuery defaultQuery, ModelAndView mv, String queryView) {
        mv.setViewName("work/list/customerservice/list");

        // 默认显示查询条件
        if (Objects.isNull(queryView)) {
            queryView = OmsPageConsts.QUERY_TAB_PRECISION_VIEW_NAME;
        }
        mv.addObject("hideQueryView", GlobalConsts.NO);

        // 下单日期
        mv.addObject("startTime", DateUtil.toString(DateUtil.getNow(), "yyyy-MM-dd 00:00:00"));
        mv.addObject("endTime", DateUtil.toString(DateUtil.getNow(), "yyyy-MM-dd 23:59:59"));

        // 回访日期
        mv.addObject("replyVisitTimeStart", DateUtil.dateFormatToString(DateUtil.getMonthFirstDay(DateUtil.getNow()), DateUtil.FORMAT_DEFAULT, DateUtil.FORMAT_DATE));
        mv.addObject("replyVisitTimeEnd", DateUtil.toString(DateUtil.getNow(), "yyyy-MM-dd 23:59:59"));

        super.setDayLimit(mv);

        List<TabQueryVO> tabList = Lists.newArrayList();

        // 精准查询
        tabList.add(TabQueryVO.builder().tabType(OmsPageConsts.QUERY_TAB_PRECISION).tabTypeName(OmsPageConsts.QUERY_TAB_PRECISION_NAME)
                .queryView(OmsPageConsts.QUERY_TAB_PRECISION_VIEW_NAME).autoQuery(GlobalConsts.YES).build());

        // 我录入的
        if (StaffAdminService.isPermitted("/zs/customerservice/work/query/my/input.action")) {
            tabList.add(TabQueryVO.builder().tabType(OmsPageConsts.QUERY_TAB_MY_INPUT).tabTypeName(OmsPageConsts.QUERY_TAB_MY_INPUT_NAME)
                    .queryView(OmsPageConsts.QUERY_TAB_MY_INPUT_VIEW_NAME).autoQuery(GlobalConsts.NO).build());
        }

        // 我回访的
        if (StaffAdminService.isPermitted("/zs/customerservice/work/query/my/reply.action")) {
            tabList.add(TabQueryVO.builder().tabType(OmsPageConsts.QUERY_TAB_MY_VISIT).tabTypeName(OmsPageConsts.QUERY_TAB_MY_VISIT_NAME)
                    .queryView(OmsPageConsts.QUERY_TAB_MY_VISIT_VIEW_NAME).autoQuery(GlobalConsts.NO).build());
        }

        mv.addObject("tabList", tabList);
        mv.addObject("queryView", queryView);

        // 默认查询条件
        mv.addObject("query", defaultQuery);
        return mv;
    }

    /**
     * 工单列表 ajax
     */
//    @RequiresPermissions("/zs/customerservice/work/list.action")
    @PostMapping(value = "/ajax/list")
    @ResponseBody
    public ResultDTO ajaxList(@NotNull @RequestBody OrderWorkQuery query) {
        // 处理tab查询
        processTagTypeQuery(query);

        //  处理查询条件
        processSearchQuery(query);

        List<ZsOrderWorkCustomerServiceVO> voList = zsOrderWorkCustomerServiceQueryBService.listPageOrderWorkByQuery(query);
        LayuiTableResponseDTO data = LayuiTableResponseDTO.success(query.getTotalCount(), voList);
        return ResultDTO.success(data);
    }

    /**
     * 呼叫系统，工单列表 ajax
     */
    @RequestMapping(value = "/ajax/orderList")
    @ResponseBody
    public ResultDTO ajaxOrderList(OrderWorkQuery query) {
        // logger.info("WorkCustomerServiceListController#ajaxOrderList query【{}】", query);
        List<ZsOrderWorkCustomerServiceVO> voList = zsOrderWorkCustomerServiceQueryBService.listPageOrderWorkByQuery(query);
        LayuiTableResponseDTO data = LayuiTableResponseDTO.success(query.getTotalCount(), voList);
        return ResultDTO.success(data);
    }


    /**
     * 工单,单条 ajax
     */
//    @RequiresPermissions("/zs/customerservice/work/list.action")
    @GetMapping(value = "/ajax/row")
    @ResponseBody
    public ResultDTO ajaxRow(@Validated OrderWorkQuery query) {
        //  处理查询条件
        processSearchQuery(query);
        List<ZsOrderWorkCustomerServiceVO> voList = zsOrderWorkCustomerServiceQueryBService.listPageOrderWorkByQueryNoRecord(query);
        if (CollectionUtils.isEmpty(voList)) {
            return null;
        }

        return ResultDTO.success(voList.get(0));
    }

    /**
     * 处理tab 查询
     *
     * @param query
     */
    @Override
    void processTagTypeQuery(OrderWorkQuery query) {
        Integer tabType = query.getTabType();
        Integer staffId = getCurrentStaff().getStaffId();

        if (tabType != null) {
            switch (tabType) {
                case OmsPageConsts.QUERY_TAB_WAIT_VISIT:
                    // 待回访
                    query.setReplyVisited(GlobalConsts.NO);
                    return;
                case OmsPageConsts.QUERY_TAB_MY_INPUT:
                    // 我录入的
                    OrderWorkOperateQuery inputOperate = new OrderWorkOperateQuery();
                    inputOperate.setOperatorId(staffId);
                    inputOperate.setOperateType(OrderConsts.ORDER_OP_TYPE_INPUT);
                    query.setOperate(inputOperate);
                    return;
                case OmsPageConsts.QUERY_TAB_MY_VISIT:
                    // 我回访的
                    OrderWorkOperateQuery replyOperate = new OrderWorkOperateQuery();
                    replyOperate.setOperatorId(staffId);
                    replyOperate.setOperateType(OrderConsts.ORDER_OP_TYPE_REPLY_VISIT);
                    query.setOperate(replyOperate);
                    return;
                default:
                    // 不处理
            }
        }
    }

    /**
     * 处理查询条件
     *
     * @param query
     */
    private void processSearchQuery(OrderWorkQuery query) {
        // 脱敏
        // query.setIsSensitiveAddr(!StaffAdminService.isPermitted(OrderPremissionConsts.getOrderWorkListAddressPermitUrl(OrderPremissionConsts.MODULE_ID_ZS_CUSTOMERSERVICE)));
        query.setIsSensitiveAddr(true);
        query.setIsSensitiveTel(true);

        // 查询下单平台是啄木鸟的
        query.setPlat(GlobalConsts.PLAT_MARK_ZMN);

        // 不查数据权限
        query.setPermit(GlobalConsts.NO);

        // 查询手机号对应的用户
        query.setQueryConcatPhoneUsers(true);
    }
}